package com.matt.controller;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.dotflat.fin.PO.FinPlanOrderPO;
import com.dotflat.fin.domain.FinPlanOrder;
import com.dotflat.fin.service.FinPlanOrderService;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.domain.Clientele;
import com.matt.domain.Contract;
import com.matt.domain.ContractProduct;
import com.matt.domain.Product;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.StatusResponse;
import com.matt.foundation.utils.CopyUtils;
import com.matt.foundation.vo.ContractVo;
import com.matt.remoteCall.SsoCallService;
import com.matt.repository.ProductRepository;
import com.matt.service.ClienteleService;
import com.matt.service.ContractService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/other_system/pay/order")
@Api(tags = "其他系统 - 待支付账单")
public class OtherSystemPayOrderController {

    @Autowired
    FinPlanOrderService finPlanOrderService;

    @Autowired
    ContractService contractService;

    @Autowired
    ProductRepository productRepository;

    @Autowired
    ClienteleService clienteleService;

    @Autowired
    SsoCallService ssoCallService;

    @ApiOperation(value = "获取账单列表")
    @GetMapping("/list")
    public StatusResponse getList(String clienteleIds, Integer payStatus){

        List<String> ids = JSON.parseArray(clienteleIds, String.class);

        List<FinPlanOrder> orders = finPlanOrderService.findAllByClienteleIds(ids, payStatus, 0, 0);

        List<FinPlanOrderPO> ret = orders.stream().map(o->{
            FinPlanOrderPO po = new FinPlanOrderPO();
            Double totalAmount  = Double.valueOf(o.getTotalAmount()) /100;
            o.setTotalAmount(null);
            CopyUtils.copyProperties(o, po);
            po.setTotalAmount(totalAmount);
            return po;
        }).collect(Collectors.toList());
        return StatusResponse.success(ret);
    }

    @ApiOperation(value = "获取一个对象", response = FinPlanOrder.class)
    @GetMapping()
    public StatusResponse get(String id){

        FinPlanOrder ret = finPlanOrderService.get(id);

        ContractVo contractVo = contractService.details(ret.getContractId());
        ret.setContract(contractVo);
        FinPlanOrderPO po = new FinPlanOrderPO();
        Double totalAmount  = Double.valueOf(ret.getTotalAmount())/100;
        ret.setTotalAmount(null);
        CopyUtils.copyProperties(ret, po);
        po.setTotalAmount(totalAmount);
        return StatusResponse.success(po);
    }

    @ApiOperation(value = "获取可以独立购买的产品列表", response = Product.class)
    @GetMapping("/initiable_products")
    public StatusResponse getInitiableProducts(String crmClienteleId, String name){

        Clientele clientele = clienteleService.getById(crmClienteleId);
        if (clientele == null){
            throw new BusinessException(ErrorCode.CLIENTELE_EXIST, "客户不存在");
        }

        List<Product> products = null;
        String areaId = clientele.getAreaId();
        if(StringUtils.isEmpty(name)){
            products = productRepository.findAllByAreaIdAndIsVisibleAndInitiableIsTrue(areaId, 1);
        }else{
            name = String.format("%%%s%%", name);
            products = productRepository.findAllByAreaIdAndIsVisibleAndNameLikeAndInitiableIsTrue(areaId, name, 1);
        }

        return StatusResponse.success(products);
    }

    @ApiOperation(value = "根据产品和数量创建独立订单", response = FinPlanOrder.class)
    @GetMapping("/create_order")
    public StatusResponse createPayOrder(String crmClienteleId, String productId, Integer count){

        Clientele clientele = clienteleService.getById(crmClienteleId);
        if (clientele == null){
            throw new BusinessException(ErrorCode.CLIENTELE_EXIST, "客户不存在");
        }

        String areaId = clientele.getAreaId();
        Product product = productRepository.findByIdAndAreaId(productId, areaId);
        if (product == null){
            throw new BusinessException(ErrorCode.PRODUCT_NOT_EXIST, "产品不存在");
        }
        if(!product.getInitiable()){
            throw new BusinessException(ErrorCode.PRODUCT_NOT_EXIST, "产品无法自行购买");
        }
        //创建订单，创建合同
        StaffDTO staff = ssoCallService.getStaffDTO(null, clientele.getStaffId());
        int totalAmount = product.getStandardAmount().intValue() * count;

        ContractProduct cp = new ContractProduct();
        cp.setProductId(productId);
        cp.setCount(count + 0.0);
        List<ContractProduct> contractProducts = new ArrayList<>();
        contractProducts.add(cp);

        String productJSON = JSON.toJSONString(contractProducts);

        Contract contract = finPlanOrderService.createContractByPlan(staff, clientele,
                null, 0, new BigDecimal(totalAmount), productJSON);

        return StatusResponse.success(contract);
    }
}
